// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UserRepository.cs" company="Concept Architecture">
//   (c) 2010 Muhammad Umer Farooq
// </copyright>
// <summary>
//   Defines the <seealso cref="UserRepository" /> type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Hisaab.Data
{
    using System;
    using System.Data.Objects;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using System.Linq.Expressions;
    using Hisaab.Data.Entities;
    using Hisaab.Data.Filters;
    using Hisaab.Data.Interfaces;

    using Microsoft.Practices.ServiceLocation;

    /// <summary>
    /// Defines the <seealso cref="UserRepository"/> type.
    /// </summary>
    public class UserRepository : IUserRepository
    {
        /// <summary>
        /// Databse instance to use
        /// </summary>
        private readonly IDatabase _database;

        /// <summary>
        /// Initializes a new instance of the <see cref="UserRepository"/> class.
        /// </summary>
        public UserRepository()
            : this(ServiceLocator.Current.GetInstance<IDatabase>())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="UserRepository"/> class.
        /// </summary>
        /// <param name="database">The database.</param>
        public UserRepository(IDatabase database)
        {
            Contract.Requires<ArgumentNullException>(database != null);
            _database = database;
        }

        /// <summary>
        /// Queries the specified filter.
        /// </summary>
        /// <param name="filter">The filter.</param>
        /// <param name="pageNo">The page no.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns>List of users</returns>
        public IQueryable<User> Query(User filter, int? pageNo, int? pageSize)
        {
            return _database.Users
                .Filter(filter)
                .Page(pageNo, pageSize);
        }

        /// <summary>
        /// Filters the specified filter.
        /// </summary>
        /// <param name="filter">The filter.</param>
        /// <param name="pageNo">The page no.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns>List of users</returns>
        public IQueryable<User> Filter(Expression<Func<User, bool>> filter, int? pageNo, int? pageSize)
        {
            return _database.Users
                .Where(filter)
                .Page(pageNo, pageSize);
        }

        /// <summary>
        /// Finds the by id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns>User by id</returns>
        public User FindById(int id)
        {
            return _database.Users
                .Filter(new User { Id = id })
                .FirstOrDefault();
        }

        /// <summary>
        /// Adds the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns>Id of new item</returns>
        public int Add(User entity)
        {
            _database.Users.AddObject(entity);
            _database.SaveChanges();
            _database.Refresh(RefreshMode.StoreWins, entity);
            return entity.Id;
        }

        /// <summary>
        /// Updates the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void Update(User entity)
        {
            var previousEntity = _database.Users.Filter(new User { Id = entity.Id }).FirstOrDefault();

            if (previousEntity != null)
            {
                previousEntity.Name = entity.Name;
            }

            _database.SaveChanges();
        }

        /// <summary>
        /// Deletes the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void Delete(User entity)
        {
            var previousEntity = _database.Users.Filter(new User { Id = entity.Id }).FirstOrDefault();

            if (previousEntity != null)
            {
                _database.Users.DeleteObject(previousEntity);
            }

            _database.SaveChanges();
        }

        /// <summary>
        /// Validates the useer.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <returns>
        /// Id of user if authentication successful, -1 if authentication fails
        /// </returns>
        public int ValidateUser(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                return -1;
            }

            var user = _database.Users
                .Where(x => x.Name.Equals(username, StringComparison.InvariantCultureIgnoreCase) && x.Password.Equals(password))
                .SingleOrDefault();

            if (user != null)
            {
                return user.Id;
            }

            return -1;
        }
    }
}